import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../models/dateline_event.dart';

/// 时间线服务提供者
final datelineServiceProvider = Provider<DatelineService>((ref) {
  // 创建用于时间线API的Dio实例
  final dio = Dio(BaseOptions(
    baseUrl: 'http://10.0.2.2:9092',  // 时间线服务的域名和端口
    connectTimeout: const Duration(seconds: 5),
    receiveTimeout: const Duration(seconds: 30),
    headers: {
      'Content-Type': 'application/json',
      'Accept': '*/*',
      'User-Agent': 'FamilyApp/1.0.0',
      'Connection': 'keep-alive',
    },
  ));
  
  // 添加日志拦截器，方便调试
  dio.interceptors.add(LogInterceptor(
    requestBody: true,
    responseBody: true,
    requestHeader: true,
    responseHeader: false,
  ));
  
  return DatelineService(dio);
});

/// 时间线服务类
class DatelineService {
  final Dio _dio;

  DatelineService(this._dio);

  /// 创建时间线事件
  Future<DatelineEvent?> createEvent(DatelineEvent event) async {
    try {
      print('正在创建时间线事件: ${event.title}');
      
      // 准备请求数据
      final requestData = event.toApiRequest();
      
      print('请求数据: $requestData');
      
      // 调用后端接口创建时间线事件
      final response = await _dio.post(
        '/api/dateline/create',
        data: requestData,
      );

      print('响应状态码: ${response.statusCode}');
      print('响应数据: ${response.data}');

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        // 检查响应格式
        if (responseData is Map<String, dynamic>) {
          // 如果响应包含成功标识
          if (responseData.containsKey('success') && responseData['success'] == true) {
            // 返回创建的事件（可能包含服务器生成的ID）
            if (responseData.containsKey('data') && responseData['data'] is Map<String, dynamic>) {
              return DatelineEvent.fromJson(responseData['data']);
            } else {
              // 如果没有返回数据，使用原始事件数据
              return event.copyWith(id: DateTime.now().millisecondsSinceEpoch.toString());
            }
          }
          // 如果响应包含code字段
          else if (responseData.containsKey('code')) {
            final code = responseData['code'];
            if (code == 200 || code == '200' || code == 'success') {
              // 检查data字段的类型
              if (responseData.containsKey('data')) {
                final data = responseData['data'];
                // 如果data是Map，则解析为事件对象
                if (data is Map<String, dynamic>) {
                  return DatelineEvent.fromJson(data);
                }
                // 如果data是true/false/其他基本类型，表示操作成功
                else if (data is bool || data is String || data is int) {
                  print('创建时间线事件成功，返回数据: $data');
                  return event.copyWith(id: DateTime.now().millisecondsSinceEpoch.toString());
                }
              }
              // 没有data字段或data为null，假设创建成功
              return event.copyWith(id: DateTime.now().millisecondsSinceEpoch.toString());
            } else {
              print('创建时间线事件失败，错误代码: $code');
              if (responseData.containsKey('message')) {
                print('错误信息: ${responseData['message']}');
              }
              return null;
            }
          }
          // 如果响应直接包含事件数据
          else if (responseData.containsKey('id') || responseData.containsKey('title')) {
            return DatelineEvent.fromJson(responseData);
          }
          // 其他情况，假设创建成功
          else {
            print('创建成功，但响应格式未知，使用原始数据');
            return event.copyWith(id: DateTime.now().millisecondsSinceEpoch.toString());
          }
        } else {
          // 如果响应不是JSON对象，假设创建成功
          print('创建成功，响应格式为非JSON对象');
          return event.copyWith(id: DateTime.now().millisecondsSinceEpoch.toString());
        }
      } else {
        print('创建时间线事件失败，状态码: ${response.statusCode}');
        return null;
      }
      
      return null;
    } catch (e) {
      print('创建时间线事件异常: $e');
      if (e is DioException) {
        print('DioException详情:');
        print('  类型: ${e.type}');
        print('  消息: ${e.message}');
        if (e.response != null) {
          print('  响应状态码: ${e.response?.statusCode}');
          print('  响应数据: ${e.response?.data}');
        }
      }
      return null;
    }
  }

  /// 获取所有时间线事件
  Future<List<DatelineEvent>> getAllEvents() async {
    try {
      print('正在获取所有时间线事件');
      
      // 调用后端接口获取所有时间线事件
      final response = await _dio.get('/api/dateline/list');

      print('响应状态码: ${response.statusCode}');
      print('响应数据: ${response.data}');

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData is Map<String, dynamic>) {
          // 检查是否有code字段表示成功
          if (responseData.containsKey('code') && 
              (responseData['code'] == 200 || responseData['code'] == '200')) {
            
            // 检查data字段中是否有records数组（API返回格式：{code: 200, data: {records: [...]}}）
            if (responseData.containsKey('data') && responseData['data'] is Map<String, dynamic>) {
              final dataMap = responseData['data'] as Map<String, dynamic>;
              if (dataMap.containsKey('records') && dataMap['records'] is List) {
                final List<dynamic> eventsData = dataMap['records'];
                return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
              }
            }
            // 检查data字段是否直接是数组
            else if (responseData.containsKey('data') && responseData['data'] is List) {
              final List<dynamic> eventsData = responseData['data'];
              return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
            }
          }
          // 检查是否有data字段（兼容其他格式）
          else if (responseData.containsKey('data')) {
            final data = responseData['data'];
            if (data is List) {
              return data.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
            } else if (data is Map<String, dynamic> && data.containsKey('records')) {
              final List<dynamic> eventsData = data['records'];
              return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
            }
          }
        } else if (responseData is List) {
          // 如果响应直接是数组
          return responseData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取时间线事件异常: $e');
      if (e is DioException) {
        print('DioException详情:');
        print('  类型: ${e.type}');
        print('  消息: ${e.message}');
        if (e.response != null) {
          print('  响应状态码: ${e.response?.statusCode}');
          print('  响应数据: ${e.response?.data}');
        }
      }
      return [];
    }
  }

  /// 根据日期获取时间线事件
  Future<List<DatelineEvent>> getEventsByDate(DateTime date) async {
    try {
      print('正在获取指定日期的时间线事件: ${date.toIso8601String()}');
      
      final formattedDate = date.toIso8601String().split('T')[0]; // YYYY-MM-DD格式
      
      // 调用后端接口获取指定日期的时间线事件
      final response = await _dio.get('/api/dateline/list', queryParameters: {
        'date': formattedDate,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('data') && responseData['data'] is List) {
            final List<dynamic> eventsData = responseData['data'];
            return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
          }
        } else if (responseData is List) {
          return responseData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
        }
      }
      
      return [];
    } catch (e) {
      print('获取指定日期的时间线事件异常: $e');
      return [];
    }
  }

  /// 根据事件类型获取时间线事件
  Future<List<DatelineEvent>> getEventsByType(DatelineEventType eventType) async {
    try {
      print('正在获取指定类型的时间线事件: ${eventType.displayName}');
      
      // 调用后端接口获取指定类型的时间线事件
      final response = await _dio.get('/api/dateline/list', queryParameters: {
        'eventTypeId': eventType.id.toString(),
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData is Map<String, dynamic>) {
          // 检查响应数据结构：{code, message, data: {records: [...], ...}}
          if (responseData.containsKey('data') && responseData['data'] is Map<String, dynamic>) {
            final dataMap = responseData['data'] as Map<String, dynamic>;
            if (dataMap.containsKey('records') && dataMap['records'] is List) {
              final List<dynamic> eventsData = dataMap['records'];
              print('解析到 ${eventsData.length} 条时间线事件');
              return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
            }
          } else if (responseData.containsKey('data') && responseData['data'] is List) {
            // 兼容直接返回列表的情况
            final List<dynamic> eventsData = responseData['data'];
            print('解析到 ${eventsData.length} 条时间线事件');
            return eventsData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
          }
        } else if (responseData is List) {
          // 兼容直接返回列表的情况
          print('解析到 ${responseData.length} 条时间线事件');
          return responseData.map((eventData) => DatelineEvent.fromJson(eventData)).toList();
        }
      }
      
      print('未能解析时间线事件数据');
      return [];
    } catch (e) {
      print('获取指定类型的时间线事件异常: $e');
      return [];
    }
  }

  /// 更新时间线事件
  Future<DatelineEvent?> updateEvent(DatelineEvent event) async {
    try {
      print('正在更新时间线事件: ${event.title}');
      
      if (event.id == null) {
        print('无法更新事件：事件ID为空');
        return null;
      }
      
      // 准备请求数据
      final requestData = event.toApiRequest();
      requestData['id'] = event.id;
      
      // 调用后端接口更新时间线事件
      final response = await _dio.post('/api/dateline/update', data: requestData);

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('success') && responseData['success'] == true) {
            if (responseData.containsKey('data') && responseData['data'] is Map<String, dynamic>) {
              return DatelineEvent.fromJson(responseData['data']);
            } else {
              return event;
            }
          } else if (responseData.containsKey('code') && 
                     (responseData['code'] == 200 || responseData['code'] == '200')) {
            if (responseData.containsKey('data')) {
              final data = responseData['data'];
              // 如果data是Map，则解析为事件对象
              if (data is Map<String, dynamic>) {
                return DatelineEvent.fromJson(data);
              }
              // 如果data是其他类型（bool/String等），表示操作成功
              else {
                print('更新时间线事件成功，返回数据: $data');
                return event;
              }
            } else {
              return event;
            }
          }
        }
        
        // 假设更新成功
        return event;
      }
      
      return null;
    } catch (e) {
      print('更新时间线事件异常: $e');
      return null;
    }
  }

  /// 删除时间线事件
  Future<bool> deleteEvent(String eventId) async {
    try {
      print('正在删除时间线事件: $eventId');
      
      // 调用后端接口删除时间线事件
      final response = await _dio.post('/api/dateline/delete', queryParameters: {
        'id': eventId,
      });

      if (response.statusCode == 200 && response.data != null) {
        final responseData = response.data;
        
        if (responseData is Map<String, dynamic>) {
          if (responseData.containsKey('success') && responseData['success'] == true) {
            return true;
          } else if (responseData.containsKey('code') && 
                     (responseData['code'] == 200 || responseData['code'] == '200')) {
            // 删除成功，无论data是什么类型
            print('删除时间线事件成功');
            return true;
          }
        }
        
        // 假设删除成功
        return true;
      }
      
      return false;
    } catch (e) {
      print('删除时间线事件异常: $e');
      return false;
    }
  }
}